package com.situ.blog.dao.impl;

import com.situ.blog.dao.ITypeDao;
import com.situ.blog.pojo.entity.Type;
import com.situ.blog.pojo.query.TypeQuery;
import com.situ.blog.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;

public class TypeDaoImpl implements ITypeDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public List<Type> selectByPage(TypeQuery typeQuery) {
        String sql = "select * from type where 1=1";
        List<Object> querList = new ArrayList<>();
        String queryType = typeQuery.getType();
        if (queryType !=null && !queryType.equals("")) {
            sql += " and type like ?";
            querList.add("%" + queryType + "%");
        }
        sql += " limit ?,?";
        int offset = (typeQuery.getPage() - 1) * typeQuery.getLimit();
        querList.add(offset);
        querList.add(typeQuery.getLimit());
        List<Type> list = template.query(sql, new BeanPropertyRowMapper<>(Type.class), querList.toArray());
        return list;
    }

    @Override
    public int selectTotalCount(TypeQuery typeQuery) {
        String sql = "select count(*) from type where 1=1";
        List<Object> queryList = new ArrayList<>();
        String queryType = typeQuery.getType();
        if (queryType !=null && !queryType.equals("")) {
            sql += " and type like ?";
            queryList.add("%" + queryType + "%");
        }
        Integer count = template.queryForObject(sql, Integer.class, queryList.toArray());
        return count;
    }

    @Override
    public void add(Type type) {
        template.update("insert into type(type) value(?)", type.getType());
    }

    @Override
    public void deleteById(Integer id) {
        template.update("delete from type where id=?", id);
    }

    @Override
    public Type selectById(Integer id) {
        return template.queryForObject("select * from type where id=?", new BeanPropertyRowMapper<>(Type.class), id);
    }

    @Override
    public void update(Type type) {
        template.update("update type set type=? where id=?", type.getType(), type.getId());
    }

    @Override
    public List<Type> selectAll() {
        return template.query("select * from type", new BeanPropertyRowMapper<>(Type.class));
    }
}
